import h5Copy from '@/common/junyi-h5-copy.js'

//复制链接
function handleCopy(content) {
  let that = this
  that.activeShow = false
  // #ifdef APP-PLUS
  uni.setClipboardData({
    data: content,
    complete() {
      that.$u.toast('复制成功')
      // plus.nativeUI.toast('复制成功', {
      //   background: '#fff',
      //   color: '#000',
      // })
    }
  })
  // #endif
  // #ifdef H5
  const result = h5Copy(content)
  if (result) {
    that.$u.toast('复制成功')
  } else {
    that.$u.toast('暂不支持复制')
  }
  // #endif
}

/**
 * 格式化时间日期
 * @param {Date} date
 * @return {String} 2020-02-04 13:30:33
 * */

function formatTime(date) {
  let year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = date.getDate()

  let hour = date.getHours()
  let minute = date.getMinutes()
  let second = date.getSeconds();


  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
/**
 * 格式化数字
 * @param {number} n
 * @return {String} 0n
 * */
function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 生成guid
 * @return {String} guid
 * */
function createGuid() {
  let s = []
  const hexDigits = '0123456789abcdef'

  for (let i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
  }

  s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = '-'

  return s.join('')
}

/**
 * 选择图片
 * @param {Number} count 1
 * @param {Object} useCamera true
 */

function chooseImages(count = 1, useCamera = true) {
  const sourceType = useCamera ? ['album', 'camera'] : ["album"];
  return new Promise((reslove, recject) => {
    uni.chooseImage({
      count: count, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: sourceType, //从相册选择
      success: (res) => {
        reslove(res);
      },
      fail: (err) => {
        recject(err)
      }
    });
  })
}

/**
 * @param {array<string>} urls  
 * @param {array<string>} longPressItemList default:  ['发送给朋友', '保存图片', '收藏']
 * */
// function previewImages(urls, current, longPressItemList = ['发送给朋友', '保存图片', '收藏']) {
function previewImages(urls, current, longPressItemList = ['保存图片到相册']) {
  return new Promise((reslove, recject) => {
    console.log(urls)
    uni.previewImage({
      urls: urls,
      loop: true,
      current,
      longPressActions: {
        itemList: longPressItemList,
        success: (data) => {
          reslove(data);
          console.log(data)
          uni.saveImageToPhotosAlbum({
            filePath: urls[current || 0],
            success: () => {
              uni.showToast({
                title: '保存图片成功，快去分享吧~',
                icon: 'none'
              })
            },
            fail: () => {
              uni.showToast({
                title: '保存失败~',
                icon: 'none'
              })
            }
          });
        },
        fail: (err) => {
          recject(err);
        }
      }
    });
  })
}

/**
 * 用户扫码
 * 不支持h5
 * 异步方法
 * */
function scanQrCode() {
  // 允许从相机和相册扫码
  return new Promise((reslove, recject) => {
    uni.scanCode({
      success: (res) => {
        reslove(res);
      },
      fail: (err) => {
        recject(err);
      }
    });
  })
}

function getRandomColor() {
  var color = "#" + Math.floor(Math.random() * 0xFFFFFF).toString(16).padStart(6, "0");
  return color;
}

//判断是否登录 judge:（默认值） 如果未登录询问是否登录  force：未登录直接强制登录
// function judgeLogin(callback, type = "judge") {
//   //获取用户信息，判断是否登录
//   let user = uni.getStorageSync("token");
//   if (user) {
//     callback();
//   } else if (!user) {
//     if (type == "force") {
//       uni.navigateTo({
//         url: '/pages/login/login',
//         animationType: 'slide-in-bottom',
//         animationDuration: 300
//       });
//     } else {
//       uni.showModal({
//         title: "提示",
//         content: "您还未登录，请先登录~",
//         confirmText: "去登录",
//         cancelText: "再逛会",
//         success: (res) => {
//           if (res.confirm) {
//             uni.navigateTo({
//               url: '/pages/login/login',
//               animationType: 'slide-in-bottom',
//               animationDuration: 300
//             });
//           }
//         }
//       })
//     }
//   }
// }

// 根据浏览器内核图像渲染 生成浏览器唯一标识 不同浏览器内核 标识不同
function cans() {
  var canvas = document.createElement('canvas');
  var ctx = canvas.getContext('2d');
  var txt = 'http://security.tencent.com/';
  ctx.textBaseline = "top";
  ctx.font = "14px 'Arial'";
  ctx.textBaseline = "tencent";
  ctx.fillStyle = "#f60";
  ctx.fillRect(125, 1, 62, 20);
  ctx.fillStyle = "#069";
  ctx.fillText(txt, 2, 15);
  ctx.fillStyle = "rgba(102, 204, 0, 0.7)";
  ctx.fillText(txt, 4, 17);

  var b64 = canvas.toDataURL().replace("data:image/png;base64,", "");
  var bin = atob(b64);
  var crc = bin2hex(bin.slice(-16, -12));
  //var crc = bin.slice(-16,-12);
  console.log('查看浏览器唯一标识', crc)
  return crc
}

function bin2hex(str) {
  var result = "";
  for (let i = 0; i < str.length; i++) {
    result += int16_to_hex(str.charCodeAt(i));
  }
  return result;
}

function int16_to_hex(i) {
  var result = i.toString(16);
  var j = 0;
  while (j + result.length < 4) {
    result = "0" + result;
    j++;
  }
  return result;
}

//获取客户端ID
function getClientId() {
  //获取客户端ID和版本号
  var clientid = '';
  // #ifdef  H5
  // 获取equipmentId
  clientid = cans()
  // #endif

  // #ifdef APP-PLUS
  // 苹果系统
  plus.device.getInfo({
    success: function(e) {
      clientid = e.uuid;
    },
    fail: function(e) {
      console.log(e);
    }
  });
  if (!clientid) {
    // 安卓系统
    plus.device.getAAID({
      success: function(e) {
        clientid = e.aaid;
      },
      fail: function(e) {
        console.log(e);
      }
    });
  }
  if (!clientid) {
    //老版本、安卓模拟器
    if (clientid == '') {
      clientid = plus.device.uuid;
    }
  }

  // #endif
  uni.setStorageSync('equipmentId', clientid);
  return clientid;
}


function phoneNumber(phoneNumber) {
  console.log(phoneNumber)
  uni.makePhoneCall({
    phoneNumber
  });
}

function hex2int(str) {
  // console.log('查看tokenIndex', str)
  let str1 = str.substr(2)
  // console.log(str1)
  let hex = str1.toUpperCase()
  // console.log('查看16进制', hex)
  var len = hex.length,
    a = new Array(len),
    code;
  for (var i = 0; i < len; i++) {
    code = hex.charCodeAt(i);
    if (48 <= code && code < 58) {
      code -= 48;
    } else {
      code = (code & 0xdf) - 65 + 10;
    }
    a[i] = code;
  }

  return a.reduce(function(acc, c) {
    acc = 16 * acc + c;
    return acc;
  }, 0);
}


// export Vue plugins
export default function install(Vue, vm) {
  Vue.prototype.$formatTime = formatTime;
  Vue.prototype.$createGuid = createGuid;
  Vue.prototype.$chooseImages = chooseImages;
  Vue.prototype.$previewImages = previewImages;
  Vue.prototype.$scanQrCode = scanQrCode;
  Vue.prototype.$getRandomColor = getRandomColor;
  Vue.prototype.$handleCopy = handleCopy;
  // Vue.prototype.$judgeLogin = judgeLogin;
  // Vue.prototype.$cans = cans;
  // Vue.prototype.$getClientId = getClientId;
  Vue.prototype.$phoneNumber = phoneNumber;
  // Vue.prototype.$hex2int = hex2int;
}
